package project.batch.sample;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.imageio.ImageIO;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import project.batch.ProjectBatch;
import project.batch.ProjectPerform;
import project.db.model.FooMaster;

import common.db.JdbcSource;
import common.db.dao.Dao;
import common.db.dao.DaoConstraintException;

/**
 * バッチサンプルクラス
 *
 * @author Tadashi Nakayama
 * @version 1.0.0
 */
public final class Sample extends ProjectBatch {
	/** ログ出力オブジェクト */
	private static final Logger LOGGER = LogManager.getLogger(Sample.class);

	/**
	 * メイン処理
	 *
	 * @param args 引数
	 */
	public static void main(final String... args) {
		int ret = ProjectPerform.start(Sample.class, args);
		Runtime.getRuntime().exit(ret);
	}

	/**
	 * @see batch.base.Batch#perform(java.lang.String...)
	 */
	@Override
	public int perform(final String... args) {
		LOGGER.debug("start perform");

		try (Dao dao = JdbcSource.getDao()) {
			FooMaster fm = new FooMaster();
			fm.setInsertDatetime(super.getParameter().getDateTime());
			fm.setInsertId("createUserId");
			fm.setFooAddress("fooAddress");
			fm.setFooId("fooId");
			fm.setFooName("fooName");
			fm.setFooPhone("030303030");
			fm.setHooId("hooId");
			fm.setTorokuDatetime(super.getParameter().getDateTime());
			fm.setUpdateDatetime(super.getParameter().getDateTime());
			fm.setUpdateId("updateUserId");
			fm.setVersion(1);
//			fm.setId(Long.valueOf(5));
			dao.insert(fm);

			dao.commit();
		} catch (final DaoConstraintException ex) {
			LOGGER.warn(ex.getMessage());
		}

		// サムネイル
		int height = 480;
		int width = 640;
		try (FileInputStream fis = new FileInputStream("./original.jpg")) {
			BufferedImage image = ImageIO.read(fis);
			BufferedImage shrinkImage = new BufferedImage(width, height, image.getType());
			shrinkImage.getGraphics().drawImage(image.getScaledInstance(
							width, height, Image.SCALE_AREA_AVERAGING), 0, 0, width, height, null);
			ImageIO.write(shrinkImage, "jpg", new File("./2.jpg"));
		} catch (final IOException ex) {
			LOGGER.error(ex.getMessage(), ex);
		}

		this.addFile("c:\\temp\\aaa.txt", "AAA");
		this.addFile("c:\\temp\\bbb.txt", "BBB");

		LOGGER.debug("end perform");

		return RET_SUCCESS;
	}

	/**
	 * @see batch.base.Batch#getBatchName()
	 */
	@Override
	public String getBatchName() {
		return "SAMPLE";
	}
}
